package org.flint92.springboot.mbean.dynamic;

import javax.management.*;

import static javax.management.MBeanOperationInfo.ACTION;

/**
 * @author flint92
 */
public class SimpleDynamicMBean implements DynamicMBean {

    private String value;

    @Override
    public Object getAttribute(String attribute) {
        return value;
    }

    @Override
    public void setAttribute(Attribute attribute) {
        String attributeName = attribute.getName();
        if ("value".equals(attributeName)) {
            this.value = (String) attribute.getValue();
        }
    }

    @Override
    public AttributeList getAttributes(String[] attributes) {
        return null;
    }

    @Override
    public AttributeList setAttributes(AttributeList attributes) {
        return null;
    }

    @Override
    public Object invoke(String actionName, Object[] params, String[] signature)
            throws MBeanException, ReflectionException {

        if ("displayValue".equals(actionName)) {
            return this.value;
        }
        return null;
    }

    @Override
    public MBeanInfo getMBeanInfo() {

        MBeanInfo beanInfo = new MBeanInfo(
                this.getClass().getName(),
                "custom dynamic MBean",
                of(new MBeanAttributeInfo("value", String.class.getName(), "custom value attr", true, true, false)),
                of(new MBeanConstructorInfo(this.getClass().getSimpleName(), "default constructor",
                        new MBeanParameterInfo[0])),
                of(new MBeanOperationInfo("displayValue", "custom displayValue method", new MBeanParameterInfo[0],
                        String.class.getName(), ACTION)),
                new MBeanNotificationInfo[0]
        );
        return beanInfo;
    }

    @SafeVarargs
    private final <T> T[] of(T... args) {
        return args;
    }

}
